package com.api.service.impl;

import com.api.entity.Token;
import com.api.mapper.TokenMapper;
import com.api.service.TokenService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 用户Token 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-10
 */
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token> implements TokenService {


    @Resource
    private TokenMapper tokenDao;

    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 3600 * 12;

    @Override
    public Token getByToken(String token) {
        QueryWrapper<Token> wq = new QueryWrapper<>();
        wq.eq("token", token);
        return tokenDao.selectOne(wq);
    }
    @Override
    public Token createToken(Long userId) {
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //用户token
        String token;

        //判断是否生成过token
        QueryWrapper<Token> wq = new QueryWrapper<>();
        wq.eq("user_id",userId);

        Token tokenEntity = tokenDao.selectOne(wq);
        if(tokenEntity == null){
            //生成一个token
            token = generateToken();
            tokenEntity = new Token();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            //保存token
            tokenDao.insert(tokenEntity);
        }else{
            //判断token是否过期
            if(tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()){
                //token过期，重新生成token
                token = generateToken();
            }else {
                token = tokenEntity.getToken();
            }

            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }

        return tokenEntity;
    }

    @Override
    public void expireToken(Integer userId){
        Date now = new Date();
        LambdaUpdateWrapper<Token> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Token::getUserId, userId);
        updateWrapper.set(Token::getExpireDate, now);
        updateWrapper.set(Token::getUpdateDate, now);
        tokenDao.update(updateWrapper);
    }
    private String generateToken(){
        return UUID.randomUUID().toString().replace("-", "");
    }
}
